const fs = require('fs');
const path = require('path');
const storyModel = require('../models/story');
const bookPath = path.resolve(__dirname, '../books/');
const ctrlObj = {
	//获取小说列表记录
	getStoryList(page, callback) {
		let pages = page || 1;
		storyModel.getBookList(pages, 20, data => {
			callback(data);
		})
	},
	//获取小说单条记录
	getStoryOne(id, callback) {
		storyModel.getBookOne(id, data => {
			callback(data);
		})
	},
	//获取上传图片列表
	getImageList(callback) {
		let imgPath = path.resolve(__dirname, '../uploads/');
		fs.readdir(imgPath, (err, files) => {
			if(err) {
				console.log(err);
			} else {
				let arr = [];
				files.forEach(item => arr.push('/uploads/' + item));
				callback(arr);
			}
		})
	},
	//添加小说操作
	createStory(params, callback) {
		storyModel.getBookNo(bkno => {
			params.bookno = bkno;
			params.booksrc = path.join(bookPath, bkno);
			storyModel.createBook(params, data => {
				if(data){
					this.createBookDir(params.booksrc, () => {
						callback(data);
					})
				}else{
					callback(data);
				}
			});
		});
	},
	//编辑小说操作
	updateStory(id, params, callback) {
		delete params.id
		storyModel.updateBook(id, params, data => {
			if(!!data[0]){
				callback(true);
			}else{
				callback(false);
			}
		})
	},
	//删除小说操作
	delStory(id, callback) {
		storyModel.deleteBook(id, data => {
			if(!!data){
				callback(true);
			}else{
				callback(false);
			}
		})
	},
	//获取小说信息
	getStoryInfo(bkno, callback){
		storyModel.getBookName(bkno, data => {
			let datas = JSON.parse(data);
			this.getChapterList(datas.booksrc, result => {
				callback({
					data:datas,
					list:result
				});
			})
		});
	},
	//获取章节列表
	getChapterList(path, callback){
		let result = fs.readdirSync(path);
		callback(result);
	},
	createChapter(req, res, next) {

	},
	//编辑章节操作
	updateChapter(req, res, next) {

	},
	//同步章节操作
	syncChapter(req, res, next) {

	},
	//创建小说文件夹
	createBookDir(bkpath, callback) {
		console.log(fs.existsSync(bkpath));
		/* if(!fs.existsSync(bkpath)) {
			fs.mkdirSync(bkpath);
		}
		callback(); */
	},
	//存放章节
	saveChapterInfo(params, callback) {
		
	}
}

module.exports = ctrlObj;